<template>
  <div class="app-container">
     <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
        <el-form-item label="商品名称" prop="goodsName">
           <el-input
              v-model="queryParams.goodsName"
              placeholder="请输入商品名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
           />
        </el-form-item>
        <el-form-item label="商品分类" prop="goodsType">
           <el-select v-model="queryParams.goodsType" placeholder="商品分类" clearable style="width: 200px">
              <el-option
                 v-for="dict in goods_type"
                 :key="dict.value"
                 :label="dict.label"
                 :value="dict.value"
              />
           </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
           <el-select v-model="queryParams.goodsStatus" placeholder="商品状态" clearable style="width: 200px">
              <el-option
                 v-for="dict in goods_status"
                 :key="dict.value"
                 :label="dict.label"
                 :value="dict.value"
              />
           </el-select>
        </el-form-item>
        <el-form-item>
           <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
           <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
     </el-form>

     <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
           <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['goods:index:add']"
           >新增</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
           <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:post:edit']"
           >修改</el-button>
        </el-col>
        <el-col :span="1.5">
           <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:post:remove']"
           >删除</el-button>
        </el-col> -->
        <!-- <el-col :span="1.5">
           <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['goods:index:export']"
           >导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
     </el-row>

     <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="商品名称" align="left" prop="goodsName"   :show-overflow-tooltip="true" />
        <el-table-column label="状态" align="center" prop="status" width="100">
           <template #default="scope">
              <dict-tag :options="goods_status" :value="scope.row.status" />
           </template>
        </el-table-column>
        <el-table-column label="商品图片" align="center" prop="status">
           <template #default="scope">
            <ImagePreview ref="ImagePreview" :src="scope.row.picUrlsPath" :width="35" :height="35"></ImagePreview>
            <!-- src/components/ImagePreview -->
           </template>
        </el-table-column>
        <el-table-column label="商品类型" align="center" prop="goodsType" width="100" :show-overflow-tooltip="true" >
           <template #default="scope">
              <dict-tag :options="goods_type" :value="scope.row.goodsType" />
           </template>
        </el-table-column>
        <el-table-column label="商品编码" align="center" prop="goodsNo" :show-overflow-tooltip="true" >
           <template #default="scope">
              <span>{{ scope.row.goodsNo ||'-' }}</span>
           </template>
        </el-table-column>
        <el-table-column label="供应商" align="center" prop="supplierName" :show-overflow-tooltip="true" />

        <el-table-column label="商品排序" align="center" prop="sort"  :show-overflow-tooltip="true" />

        <el-table-column label="创建时间" align="center" prop="createTime" width="180" :show-overflow-tooltip="true" >
           <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
           </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
           <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['goods:index:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"  v-hasPermi="['goods:index:remove']">删除</el-button>
           </template>
        </el-table-column>
     </el-table>

     <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
     />

     <!-- 添加或修改商品对话框 -->
     <el-dialog :title="title" v-model="open" width="1007px" append-to-body>
        <div class="form_box">
          <el-form ref="goodsRef" :model="form" :rules="rules" label-width="80px">
          <el-row>
              <el-col :span="12">
                <el-form-item label="商品名称" prop="goodsName">
                  <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
                </el-form-item>
              </el-col>

              <!-- <el-col :span="12">
                <el-form-item label="商品分类" prop="categoryId">
                  <el-select
                      v-model="form.categoryId"
                      placeholder="请选择商品分类"
                      clearable
                      style="width: 240px"
                    >
                      <el-option
                        v-for="dict in classifyOptions"
                        :key="dict.categoryId"
                        :label="dict.name"
                        :value="dict.categoryId"
                      />
                    </el-select>
                </el-form-item>
              </el-col> -->
              <el-col :span="12">
                <el-form-item label="商品编码" prop="goodsNo">
                  <el-input v-model="form.goodsNo" placeholder="请输入商品编码" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
              <el-form-item label="排序" prop="sort">
                <el-input-number v-model="form.sort" controls-position="right" :min="0" ></el-input-number>
              </el-form-item>
            </el-col>
              <el-col :span="12">
                <el-form-item label="商品状态" prop="status">
                  <el-radio-group v-model="form.status">
                    <el-radio
                      v-for="dict in goods_status"
                      :key="dict.value"
                      :label="dict.value"
                    >{{dict.label}}</el-radio>
                </el-radio-group>
              </el-form-item>

              </el-col>
              <el-col :span="12">
                <el-form-item label="商品图片" prop="picUrls">
                  <ImageUpload ref="ImageUploads" v-model:modelValue="form.picUrls" ></ImageUpload>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品类型" prop="goodsType">
                  <el-radio-group v-model="form.goodsType">
                    <el-radio
                      v-for="dict in goods_type"
                      :key="dict.value"
                      :label="dict.value"
                    >{{dict.label}}</el-radio>
                </el-radio-group>
              </el-form-item>

              </el-col>
            </el-row>
            <el-row>
              <el-col :span="1.5" style="margin-left: 80px;margin-bottom: 20px;">
                  <el-button
                    type="primary"
                    plain

                    @click="handleTableAdd"
                  >添加规格</el-button>
                </el-col>
            </el-row>
            <el-row>

              <el-col :span="24">

                <el-form-item label="商品规格" >
                <el-table :data="skuList" border>
                  <el-table-column label="商品名称" align="center" prop="image" width="170" >
                    <template #default="scope">
                      <el-input v-model="scope.row.goods_sku_no" placeholder="请输入商品名称" />
                    </template>
                  </el-table-column>
                  <el-table-column label="商品图片" align="center" prop="image" width="150" >
                    <template #default="scope">
                      <ImageUpload ref="ImageUpload" v-model:modelValue="scope.row.pic_url" :limit="1" ></ImageUpload>
                    </template>
                  </el-table-column>
                  <el-table-column label="商品价格(元)" align="center" prop="image" width="120" >
                    <template #default="scope">
                      <el-input-number controls-position="right" style="width: 90px;" :min="0" v-model="scope.row.goods_price" placeholder="请输入商品价格"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column label="商品库存(个)" align="center" prop="image" width="120" >
                    <template #default="scope">
                      <el-input-number  controls-position="right" style="width: 90px;"  type="number" :min="0" v-model="scope.row.stock_num" placeholder="请输入商品库存" ></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column label="支付金额(元)" align="center" prop="image" width="120" v-if="form.goodsType == 4">
                    <template #default="scope">
                      <el-input-number controls-position="right" style="width: 90px;"  type="number" :min="0" v-model="scope.row.pay_cash" placeholder="请输入支付金额" ></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column label="饭券" align="center" prop="image" width="120" v-if="form.goodsType == 4">
                    <template #default="scope">
                      <el-input-number controls-position="right" style="width: 90px;"  type="number" :min="0" v-model="scope.row.pay_point" placeholder="请输入饭券" ></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template #default="scope">
                      <el-button
                       text
                        icon="Delete"
                        @click="handleSmallDelete(scope.$index)"
                      >删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>

              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="商品内容" prop="content">
                  <!-- <el-input v-model="form.detail" type="textarea" placeholder="请输入资讯内容" ></el-input> -->
                  <editor v-model="form.content" :min-height="220"/>
                </el-form-item>
              </el-col>
            </el-row>
        </el-form>
        </div>

        <template #footer>
           <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
           </div>
        </template>
     </el-dialog>
  </div>
</template>

<script setup name="goodsManage">

import { getGoodsList,addGoods,deleteGoods,editGoods,getGoodsDetail} from "@/api/goods/manage";
const { proxy } = getCurrentInstance();
const { goods_status,goods_type } = proxy.useDict("goods_status","goods_type");

const goodsList = ref([]);
const skuList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
 form: {},

 queryParams: {
   pageNum: 1,
   pageSize: 10,
   goodsName: undefined,
   goodsType: undefined,
   goodsStatus:undefined
 },
 rules: {
  goodsName: [
    { required: true, message: "商品名称不能为空", trigger: "blur" }
  ],
  // categoryId: [
  //   { required: true, message: "商品分类不能为空", trigger: ["blur","change"] }
  // ],
  serviceId:[
  { required: true, message: "归属服务不能为空", trigger: ["blur","change"] }
  ],
  sort:[
    { required: true, message: "商品排序不能为空", trigger: "change" }
  ],
  content:[
    { required: true, message: "商品详情不能为空", trigger: "change" }
  ],
 }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商品列表 */
function getList() {
 loading.value = true;
 getGoodsList(queryParams.value).then(response => {
   goodsList.value = response.rows;
   total.value = response.total;
   loading.value = false;
 });
}
/** 取消按钮 */
function cancel() {
 open.value = false;
 reset();
}
/** 表单重置 */
function reset() {
 form.value = {
    goodsId: undefined,
    goodsName: undefined,
    categoryId: undefined,
    goodsNo: undefined,
    memberLevel: undefined,
    sort: undefined,
    content: undefined,
    status: "0",
    picUrls:undefined,
    goodsType:'1'
 };

 proxy.resetForm("goodsRef");
}
/** 搜索按钮操作 */
function handleQuery() {
 queryParams.value.pageNum = 1;
 getList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value.goodsStatus = '';
 proxy.resetForm("queryRef");
 handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
 ids.value = selection.map(item => item.postId);
 single.value = selection.length != 1;
 multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
 reset();
 skuList.value = [];
 open.value = true;
 title.value = "添加商品";
}
/** 修改按钮操作 */
function handleUpdate(row) {
 reset();
 const goodsId =  row.goodsId;
 getGoodsDetail(goodsId).then(response => {
   response.data.status = response.data.status+'';
   response.data.goodsType =  response.data.goodsType+''
   form.value = response.data;
   title.value = "修改商品";
   skuList.value = response.data.skuList;
   open.value = true;

 });
}

function handleSmallDelete(index){
  if(skuList.value.length == 1){
    proxy.$modal.msgWarning("请添加商品");
  }else{
    skuList.value.splice(index,1)
  }

}


/** 提交按钮 */
function submitForm() {
 proxy.$refs["goodsRef"].validate(valid => {
   if (valid) {
      // console.log(form.value)
      if(form.value.picUrls===''||form.value.picUrls===undefined||form.value.picUrls===null){
        proxy.$modal.msgWarning("请添加商品图片");
        return
      }
      if(skuList.value.length == 0){
        proxy.$modal.msgWarning("请补充商品规格");
        return
      }
      for(let i= 0;i<skuList.value.length;i++){
          if(skuList.value[i].goods_sku_no ===''||skuList.value[i].goods_sku_no ===undefined||skuList.value[i].goods_sku_no ===null){
            proxy.$modal.msgWarning("请补充完整商品规格");
            return
          }
          if(skuList.value[i].goods_price ===''||skuList.value[i].goods_price ===undefined||skuList.value[i].goods_price ===null){
            proxy.$modal.msgWarning("请补充完整商品规格");
            return
          }
          if(skuList.value[i].stock_num ===''||skuList.value[i].stock_num ===undefined||skuList.value[i].stock_num ===null){
            proxy.$modal.msgWarning("请补充完整商品规格");
            return
          }
          if(skuList.value[i].pic_url ===''||skuList.value[i].pic_url ===undefined||skuList.value[i].pic_url ===null){
            proxy.$modal.msgWarning("请补充完整商品规格");
            return
          }

      }
      form.value.skuListJson = JSON.stringify(skuList.value)
     if (form.value.goodsId != undefined) {
        editGoods(form.value).then(response => {
         proxy.$modal.msgSuccess("修改成功");
         open.value = false;
         getList();
       });
     } else {
        addGoods(form.value).then(response => {
         proxy.$modal.msgSuccess("新增成功");
         open.value = false;
         getList();
       });
     }
   }
 });
}
/** 删除按钮操作 */
function handleDelete(row) {
 const goodsId = row.goodsId;
 proxy.$modal.confirm('是否确认删除名称为"' + row.goodsName + '"的数据项？').then(function() {
   return deleteGoods(goodsId);
 }).then(() => {
   getList();
   proxy.$modal.msgSuccess("删除成功");
 }).catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
 proxy.download("system/post/export", {
   ...queryParams.value
 }, `post_${new Date().getTime()}.xlsx`);
}
 /** 添加规格 */
function handleTableAdd(){
  skuList.value.push(
    {"goods_sku_no":"","pic_url":"","goods_price":0,"stock_num":0}
  )
}
getList();
</script>
<style lang="scss" scoped>
.form_box {
  height: 60vh;
  overflow: auto;
}
</style>
